package com.lazason.wib4android;

import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.text.util.Linkify;
import android.text.util.Linkify.TransformFilter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.lazason.wib4android.AsyncImageLoader.ImageCallback;

public class ListViewAdapter extends SimpleAdapter {
	List<? extends Map<String, ?>> data;
	Context context;
    private static long lastTime;
    private static long currentTime;
    
	AsyncImageLoader asyncImageLoader;
	private ListView listView;
	private LayoutInflater inflater;

	public ListViewAdapter(Context context,
			List<? extends Map<String, ?>> data, int resource, String[] from,
			int[] to, ListView listView) {
		super(context, data, resource, from, to);
		this.context = context;
		this.data = data;
		this.listView = listView;
		asyncImageLoader = new AsyncImageLoader();
		inflater = ((Activity) context).getLayoutInflater();
		// TODO Auto-generated constructor stub
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View row = convertView;
		final int pos = position;
		lastTime = System.currentTimeMillis();
		currentTime = System.currentTimeMillis();
		Holder holder; 
		if (convertView == null) {
			convertView = inflater.inflate(R.layout.listitem, null);
			holder = new Holder();
			holder.profile = (ImageView) convertView.findViewById(R.id.profile);
			holder.picture = (ImageView) convertView.findViewById(R.id.picture);
			holder.wib = (TextView) convertView.findViewById(R.id.weibo);
			holder.name = (TextView) convertView.findViewById(R.id.username);
			convertView.setTag(holder);
		} else {
			holder = (Holder) convertView.getTag();
			//holder.picture = (ImageView) convertView.findViewById(R.id.picture);
		}
		Log.d("ListViewAdapter", "get holder time elapse "+(System.currentTimeMillis()-currentTime));
		MyApplication.holderTime += System.currentTimeMillis()-currentTime;
		currentTime=System.currentTimeMillis();
		String picUrl = (String) data.get(pos).get("thumbnail_pic");
		Log.d("ListViewAdapter", "get picUrl time elapse "+(System.currentTimeMillis()-currentTime));
		MyApplication.picUrlTime += System.currentTimeMillis()-currentTime;
		currentTime=System.currentTimeMillis();
		// ImageView profile = (ImageView) row.findViewById(R.id.profile);
		String pictureId = "picture" + String.valueOf(data.get(pos).get("id"))
				+ pos;
		Log.d("ListViewAdapter", "get pictureId time elapse "+(System.currentTimeMillis()-currentTime));
		MyApplication.picUrlTime += System.currentTimeMillis()-currentTime;
		currentTime=System.currentTimeMillis();
		holder.picture.setImageDrawable(null);
		holder.picture.setTag(pictureId);
		if (picUrl != null && !picUrl.equals("")) {
			
			
			Drawable cachedPicture = asyncImageLoader.loadDrawable(context,
					picUrl, pictureId, Thread.MAX_PRIORITY,
					new ImageCallback() {
						public void imageLoaded(Drawable imageDrawable,
								String imageUrl, String id) {
							ImageView imageViewByTag = (ImageView) listView
									.findViewWithTag(id);
							Log.i("test",
									"Drawable cachedImage = asyncImageLoader.loadDrawable( )-->");
							if (imageViewByTag != null && imageDrawable != null) { // 防止图片url获取不到图片是，占位图片不见了的情况
								imageViewByTag.setImageDrawable(imageDrawable);
								imageViewByTag.setVisibility(View.VISIBLE);
								
							}
						}
					});
			if (cachedPicture == null) {
//				if(MyApplication.icon==null){
//				holder.picture.setImageResource(R.drawable.icon);
//				MyApplication.icon = holder.picture.getDrawable();
//				} else {
//					holder.picture.setImageDrawable(MyApplication.icon);
//				}
					
			} else {
				holder.picture.setImageDrawable(cachedPicture);

			}
		} 
		Log.d("ListViewAdapter", "get picture time elapse "+(System.currentTimeMillis()-currentTime));
		MyApplication.pictureTime += System.currentTimeMillis()-currentTime;
		currentTime=System.currentTimeMillis();
		
		
		holder.profile.setImageDrawable(null);
		holder.profile.setTag("profile"
				+ String.valueOf(data.get(pos).get("id")));

	

		// 延遲加載圖片 ： imageUrl 是 圖片的http鏈接地址，後面是回调函數
		Drawable cachedImage = asyncImageLoader.loadDrawable(context,
				(String) data.get(pos).get("profile"),
				"profile" + String.valueOf(data.get(pos).get("id")),
				Thread.MAX_PRIORITY, new ImageCallback() {
					public void imageLoaded(Drawable imageDrawable,
							String imageUrl, String id) {
						ImageView imageViewByTag = (ImageView) listView
								.findViewWithTag(id);
						
						if (imageViewByTag != null && imageDrawable != null) { // 防止图片url获取不到图片是，占位图片不见了的情况
							imageViewByTag.setImageDrawable(imageDrawable);

						}
					}
				});
		Log.d("ListViewAdapter", "get cachedImage for profile time elapse "+(System.currentTimeMillis()-currentTime));
		MyApplication.getCachedImageTime += System.currentTimeMillis()-currentTime;
		currentTime=System.currentTimeMillis();
		if (cachedImage == null) {
			 
			
//			if(MyApplication.icon==null){
//				holder.profile.setImageResource(R.drawable.icon);
//				MyApplication.icon = holder.profile.getDrawable();
//				} else {
//					holder.profile.setImageDrawable(MyApplication.icon);
//				}
		} else {
			holder.profile.setImageDrawable(cachedImage);
		}
		Log.d("ListViewAdapter", "set cachedImage for profile time elapse "+(System.currentTimeMillis()-currentTime));
		MyApplication.setCachedImageTime += System.currentTimeMillis()-currentTime;
		currentTime=System.currentTimeMillis();
		 
		holder.profile.setOnClickListener(new OnClickListener() {
			String id = String.valueOf(data.get(pos).get("id"));
			String screen_name = (String) data.get(pos).get("username");

			@Override
			public void onClick(View arg0) {

				Intent intent = new Intent();
				intent.putExtra("id", id);
				intent.putExtra("screen_name", screen_name);
				intent.setClass(context, FriendHomeActivity.class);
				((Activity) context).startActivity(intent);
			}

		});
		Log.d("ListViewAdapter", "set profile.setOnClickListener time elapse "+(System.currentTimeMillis()-currentTime));
		MyApplication.setProfileTime += System.currentTimeMillis()-currentTime;
		currentTime=System.currentTimeMillis();
		String weibo = (String) data.get(position).get("weibo");
		Log.d("ListViewAdapter", "get weibo time elapse "+(System.currentTimeMillis()-currentTime));
		MyApplication.getWeiboTime += System.currentTimeMillis()-currentTime;
		currentTime=System.currentTimeMillis();
		
		holder.wib.setText(weibo);
		
		
		
		if(System.currentTimeMillis()-currentTime>50){
		   Log.w("ListViewAdapter", "set weibo time elapse "+(System.currentTimeMillis()-currentTime));
		   Log.w("ListViewAdapter", weibo);
		}else{
			Log.d("ListViewAdapter", "set weibo time elapse "+(System.currentTimeMillis()-currentTime));
		}
		MyApplication.setWeiboTime += System.currentTimeMillis()-currentTime;
		currentTime=System.currentTimeMillis();
		if(weibo.indexOf("http")>=0){
			Linkify.addLinks(holder.wib, Linkify.WEB_URLS);
		}
		Log.d("ListViewAdapter", "add Linkify.WEB_URLS time elapse "+(System.currentTimeMillis()-currentTime));
		MyApplication.WEB_URLSTime += System.currentTimeMillis()-currentTime;
		currentTime=System.currentTimeMillis();
		
		holder.name.setText((String) data.get(position).get("username"));
		Log.d("ListViewAdapter", "set username time elapse "+(System.currentTimeMillis()-currentTime));
		MyApplication.usernameTime += System.currentTimeMillis()-currentTime;
		currentTime=System.currentTimeMillis();
//		int flags = Pattern.CASE_INSENSITIVE;
//		Pattern topicPattern = Pattern.compile("#(\\w+?)#");
		Pattern userPattern = Pattern.compile("@(\\w+?)(?=\\W|$)");
		String friendScheme = "wib://friendhomeactivity/?screen_name=";
//		String topicScheme = "wib://topicactivity/?topic=";
		 
		
		if(weibo.indexOf("@")>=0){
			Linkify.addLinks(holder.wib, userPattern, friendScheme, null,
					new TransformFilter() {
						@Override
						public String transformUrl(Matcher match, String url) {

							return match.group(1); // replace here with sina user
													// lookup function
						}
					});
			
		}
		
		Log.d("ListViewAdapter", "add userPattern time elapse "+(System.currentTimeMillis()-currentTime));
		MyApplication.userPatternTime += System.currentTimeMillis()-currentTime;
		currentTime=System.currentTimeMillis();
		
        	
        	Log.d("ListViewAdapter", "time elapse "+(System.currentTimeMillis()-lastTime));
		return convertView;
	}

	static class Holder {
		ImageView profile;
		ImageView picture;
		TextView name;
		TextView wib;
	}
}
